<script setup>
import { getCityCategoryService, getHotCityService, getCityIDByNameService } from '@/apis/location.js'
import { onLoad } from '@dcloudio/uni-app'
import { ref, renderList, computed } from 'vue'
import SearchComponent from '@/components/SearchComponent/SearchComponent.vue'
import amap from '@/utils/amap-wx.130.js'
import { useUserStore } from '@/stores/index.js'

const UserStore = useUserStore()

// 存储热门城市数据
const hotCityList = ref([])

// 存储城市按照首字母分类的数据
const cityCategoryList = ref([])

// 创建一个从城市大写字母的数组
const indexList = ref(['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'])

// 存储列表需要渲染的数据
const RenderingList = ref([])

// 获取到的用户地址信息
const address = ref({
	province: '',
	city: '',
	city_id: '',
	district: '',
	longitude: '',
	latitude: '',
	selectedCity: '',
	selectedCityId: ''
})

// 获取热门城市数据
const getHotCity = async () => {
	const res = await getHotCityService()
	hotCityList.value = res?.data?.map((item) => {
		return {
			city_id: item.city_id,
			name: item.name,
			is_hot: true
		}
	})
}

// 获取城市按照首字母分类的数据
const getCityCategory = async () => {
	const res = await getCityCategoryService()
	cityCategoryList.value = res.data
}

// 根据城市名称查询城市ID
const getCityID = async (data) => {
	const res = await getCityIDByNameService(data)
	address.value.city_id = res.data.city_id
}

// 将热门城市数据和城市数据合并到一个数组内
RenderingList.value = computed(() => {
	return [hotCityList.value, ...cityCategoryList.value]
})

// 初始化高德小程序SDK实例对象
const mapInstance = ref({
	amapPlugin: null,
	key: '3fcebec5948fab51dcbf82facb931883'
})

// 获取用户定位
const getUserLocation = () => {
	uni.showLoading({
		title: '获取位置信息中'
	})
	mapInstance.value.amapPlugin.getRegeo({
		success: async (data) => {
			address.value.province = data[0].regeocodeData.addressComponent.province
			address.value.city = data[0].regeocodeData.addressComponent.city
			address.value.district = data[0].regeocodeData.addressComponent.district
			address.value.longitude = data[0].longitude
			address.value.latitude = data[0].latitude

			// 定义直辖市列表处理特殊情况
			const municipality = ['北京市', '天津市', '重庆市', '上海市']
			if (municipality.includes(address.value.province)) {
				address.value.city = address.value.province
				await getCityID(address.value.province.slice(0, -1))
			} else {
				await getCityID(address.value.city.slice(0, -1))
			}

			// 将用户位置信息存入Pinia
			UserStore.setUserInfoList(address.value)
			uni.hideLoading()
		},
		fail: (info) => {
			console.log(info)
			uni.showToast({
				icon: 'error',
				title: '获取失败'
			})
		}
	})
}

// 点击选择城市时触发事件
const onClickLocation = (city_id, city_name) => {
	if (city_id && city_name) {
		address.value.selectedCity = city_name
		address.value.selectedCityId = city_id
	}

	UserStore.setUserInfoList(address.value)

	uni.switchTab({
		url: '/pages/community/community'
	})
}

// 点击当前定位城市时触发事件
const onClickCurrentCity = () => {
	if (!address.value.province && !address.value.city) {
		return uni.showToast({
			title: '请获取定位',
			icon: 'error'
		})
	}

	uni.switchTab({
		url: '/pages/community/community'
	})
}

// 页面初始化时调用函数
onLoad(() => {
	getCityCategory()
	getHotCity()
	// 高德定位服务
	mapInstance.value.amapPlugin = new amap.AMapWX({
		key: mapInstance.value.key
	})
})
</script>

<template>
	<view class="container">
		<!-- 顶部搜索框 -->
		<up-sticky offset-top="0">
			<view class="header">
				<SearchComponent></SearchComponent>

				<view class="location">
					<view>当前位置</view>
					<view class="location-container">
						<view class="left" @tap="onClickCurrentCity">
							<up-icon color="#f53b22" name="map" size="20"></up-icon>
							{{ address.city + address.district }}
						</view>
						<view class="right" @tap="getUserLocation">获取定位</view>
					</view>
				</view>
			</view>
		</up-sticky>

		<!-- indexList列表 -->
		<up-index-list :index-list="indexList" customNavHeight="156">
			<template v-for="(item, index) in RenderingList.value" :key="index">
				<!-- #ifdef APP-NVUE -->
				<up-index-anchor color="#000000" size="18" :text="indexList[index] === '#' ? '热门城市' : indexList[index]"></up-index-anchor>
				<!-- #endif -->
				<up-index-item>
					<!-- #ifndef APP-NVUE -->
					<up-index-anchor color="#000000" size="18" :text="indexList[index] === '#' ? '热门城市' : indexList[index]"></up-index-anchor>
					<!-- #endif -->
					<view class="list-container">
						<template v-for="(item2, index) in item" :key="index">
							<view v-if="item2.is_hot" class="list-item-hot" @tap="onClickLocation(item2.city_id, item2.name)">{{ item2.name }}</view>
							<view v-else class="list-item" @tap="onClickLocation(item2.city_id, item2.name)">{{ item2.name }}</view>
						</template>
					</view>
				</up-index-item>
			</template>
		</up-index-list>
	</view>
</template>

<style lang="scss" scoped>
.container {
	height: 100%;

	.header {
		width: 100%;
		height: 300rpx;
		background-color: #f8f8f8;
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;

		.location-container {
			margin-top: 20rpx;
			display: flex;
			justify-content: space-between;

			.left {
				display: flex;
				align-items: center;
				justify-content: center;
				color: #f53b22;
			}

			.right {
				color: #f53b22;
			}
		}
	}

	::v-deep .u-index-item:nth-child(1) {
		.list-container {
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			padding: 50rpx;

			.list-item-hot {
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 20rpx;
				width: 25%;
				height: 60rpx;
				border-radius: 10rpx;
				background-color: #dedede;
			}
		}
	}

	.list-item {
		display: flex;
		width: 100%;
		padding: 20rpx 24rpx;
		overflow: hidden;
		color: #000000;
		font-size: 28rpx;
		line-height: 48rpx;
		background-color: #fff;
		border-bottom: 1px solid #dedede;
	}
}
</style>
